import CodeMirror, { ReactCodeMirrorProps } from "@uiw/react-codemirror";
import { forwardRef, ForwardRefRenderFunction, ReactElement, RefObject, useImperativeHandle, useState } from "react";
import { FullscreenOutlined, FullscreenExitOutlined, EyeOutlined, EyeInvisibleOutlined } from "@ant-design/icons";
import { css } from "@emotion/css";
import { FormInstance } from "antd";

interface CodeInputProps {
	field?: string;
	formRef?: RefObject<FormInstance>;
}
export interface CodeInputRef {
	setValue: (value: string) => void;
	getValue: () => string;
}
const CodeInput: ForwardRefRenderFunction<CodeInputRef, ReactCodeMirrorProps & CodeInputProps> = (props, ref) => {
	const { field, formRef, ...remainingProps } = props;
	const [isFull, setIsFull] = useState(false);
	const [isPreview, setIspreview] = useState(false);
	const [value, setValue] = useState("");
	useImperativeHandle(ref, () => ({ setValue, getValue: () => value }), [value]);
	const getIcon = ({ onClick, icon }: { onClick: () => void; icon: ReactElement }) => (
		<div onClick={onClick} style={{ width: "24px", height: "24px" }} className="cursor-pointer hover:bg-gray-200 flex justify-center items-center">
			{icon}
		</div>
	);
	return (
		<div className={`flex overflow-hidden` + (isFull ? ` fixed w-screen h-screen left-0 top-0` : " relative")} style={isFull ? { zIndex: 9999 } : {}}>
			{isPreview && (
				<div
					className={`w-1/2 bg-white overflow-y-scroll ${isFull ? "h-screen" : `h-[${props.height}]`} ${css`
						::-webkit-scrollbar {
							width: 0;
						}
						img{
							width: 100%;
						}
					`}`}
					dangerouslySetInnerHTML={{ __html: value || "" }}
				></div>
			)}
			<CodeMirror
				className={isFull ? `${isPreview ? "w-1/2" : "w-screen"} h-screen` : `${isPreview ? "w-1/2" : "w-full"}`}
				{...remainingProps}
				value={value}
				onChange={(value, viewUpdate) => {
					setValue(value);
					remainingProps?.onChange?.(value, viewUpdate);
					field && formRef?.current?.setFieldValue(field, value);
				}}
				height={isFull ? "100vh" : props.height}
			/>
			<div className="absolute right-0 top-0 flex">
				{isPreview
					? getIcon({ onClick: () => setIspreview(false), icon: <EyeInvisibleOutlined /> })
					: getIcon({ onClick: () => setIspreview(true), icon: <EyeOutlined /> })}
				{isFull
					? getIcon({ onClick: () => setIsFull(false), icon: <FullscreenExitOutlined /> })
					: getIcon({ onClick: () => setIsFull(true), icon: <FullscreenOutlined /> })}
			</div>
		</div>
	);
};

export default forwardRef(CodeInput);
